<?php
/**
 * Created by IntelliJ IDEA.
 * User: jimmyhsu
 * Date: 2017/5/29
 * Time: 20:08
 */
date_default_timezone_set("Asia/Shanghai");
include ("../Teacher/db/conn.php");
$username = $_POST['username'];
$password = $_POST['password'];
$course_id = $_POST['course_id'];
$user_id = -1;
$sql = "select * from userinfo natural join takes where name='$username' and password='".md5($password)."' and course_id='$course_id' and position='assistant'";
$result = mysqli_query($cn, $sql);
$result_arr = mysqli_fetch_array($result);
if (mysqli_num_rows($result) > 0) {
    $user_id = $result_arr['id'];
    $file_id = 0;
    $sql = "select count(*) as f_count from sharedfile where course_id='$course_id'";
    if ($query = mysqli_query($cn, $sql)) {
        $count = mysqli_fetch_array($query)['f_count'];
        if ($count > 0) {
            $sql = "select max(f_id) as max_fid from sharedfile where course_id='$course_id'";
            if ($query = mysqli_query($cn, $sql)) {
                $row = mysqli_fetch_array($query);
                $file_id = $row['max_fid'] + 1;
            } else {
                die ('db_error');
            }
        }
    } else {
        die ('db_error');
    }


    $temp = explode(".", $_FILES["file"]["name"]);
    $name = $temp[0];
    $extension = end($temp);        // 获取文件后缀名
    $file_size = $_FILES["file"]["size"];
    if ($file_size < 102400000) { // 小于 100 Mb
        if ($_FILES["file"]["error"] > 0) {
            die("file_error: " . $_FILES["file"]["error"]);
        } else {
            $file_name = $file_id . "." . $extension;
            $file_dir = "../Teacher/file/" . $course_id;
            if (!is_dir($file_dir)) {
                mkdir($file_dir, 0777, true);
            }
            if (file_exists($file_dir . "/" . $file_name)) {
                unlink($file_dir . "/" . $file_name);
            }
            move_uploaded_file($_FILES["file"]["tmp_name"], $file_dir . "/" . $file_name);
            $sql = "insert into sharedfile values('$course_id', $file_id, '$name', $file_size, $user_id, '"
                . date("Y-m-d H:i:s") . "', '$extension')";
            if (!mysqli_query($cn, $sql)) {
                unlink($file_dir . "/" . $file_name);
                die("db_error");
            } else {
                echo "success";
            }
        }
    } else {
        die("size_exceed");
    }
} else {
    die("username = $username and password = $password , permission denied");
}